package com.sj.parksdk.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;

import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.result.databean.Data_Token;
import com.sj.parksdk.setting.Constans;
import com.sj.parksdk.utils.TokenUtils;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xrouter.annotation.Router;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.utils.CountDownButtonHelper;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.button.roundbutton.RoundButton;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xutil.common.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;

@Router(path = "/login/login")
@Page(anim = CoreAnim.none, name = "验证码登录")
public class LoginFragment extends BaseFragment {
    @BindView(R2.id.iv_logo)
    AppCompatImageView ivLogo;
    @BindView(R2.id.et_phone_number)
    MaterialEditText etPhoneNumber;
    @BindView(R2.id.et_verify_code)
    MaterialEditText etVerifyCode;
    @BindView(R2.id.btn_get_verify_code)
    RoundButton btnGetVerifyCode;
    @BindView(R2.id.btn_login)
    Button btnLogin;
    @BindView(R2.id.tv_other_logintype)
    TextView tvOtherLogintype;
    @BindView(R2.id.tv_agreement)
    TextView tvAgreement;

    private CountDownButtonHelper mCountDownHelper;

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_login;
    }

    @Override
    protected void initViews() {
        initAgreePrivacy();
        updateConfirmBt(false);
    }

    @Override
    protected void initListeners() {
        mCountDownHelper = new CountDownButtonHelper(btnGetVerifyCode, 60);
        mCountDownHelper.setOnCountDownListener(new CountDownButtonHelper.OnCountDownListener() {
            @Override
            public void onCountDown(int time) {
                btnGetVerifyCode.setText("重新获取"+time+"s");
            }

            @Override
            public void onFinished() {
                btnGetVerifyCode.setText(ResUtils.getString(R.string.xui_count_down_finish));
            }
        });
        TextChange textChange = new TextChange();
        etVerifyCode.addTextChangedListener(textChange);
        etPhoneNumber.addTextChangedListener(textChange);
    }

    private void initAgreePrivacy() {
        tvAgreement.setText(getPrivacyContent(getContext()));
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * @return 隐私政策说明
     */
    private static SpannableStringBuilder getPrivacyContent(Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder()
                .append("登录即代表同意").append(getUserPrivacyLink(context, ResUtils.getString(R.string.login_server_agreement), Constans.API_AGREEMENT))
                .append("和")
                .append(getUserPrivacyLink(context, ResUtils.getString(R.string.login_privacy_agreement), Constans.PRIVACY_AGREEMENT));
        return stringBuilder;
    }

    /**
     * @return
     */
    private static SpannableString getUserPrivacyLink(Context context, String privacyName, String privacyUrl) {
        SpannableString spannableString = new SpannableString(privacyName);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Utils.goWeb(context, privacyUrl);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        }, 0, privacyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @OnClick({R2.id.btn_get_verify_code, R2.id.btn_login, R2.id.tv_other_logintype})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_get_verify_code) {
            if (etPhoneNumber.validate()) {
                getVerifyCode(etPhoneNumber.getEditValue());
            }
        } else if (id == R.id.btn_login) {
            if (etPhoneNumber.validate() && etVerifyCode.validate()) {
                loginByVerifyCode(etPhoneNumber.getEditValue(), etVerifyCode.getEditValue());
            }
        } else if (id == R.id.tv_other_logintype) {
            gotoLoginWitdPassword();
        }
    }

    private void gotoLoginWitdPassword() {
        openPage(FragmentLoginPassword.class, false);
    }

    /**
     * 获取验证码
     */
    @SuppressLint("CheckResult")
    private void getVerifyCode(String phone) {
        mCountDownHelper.start();
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .loginSendMesg(phone, true))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        if (result.getCode() != 200) XToastUtils.error(result.getMessage());
                    }
                });
    }

    /**
     * 根据验证码登录
     *
     * @param phoneNumber 手机号
     * @param verifyCode  验证码
     */
    @SuppressLint("CheckResult")
    private void loginByVerifyCode(String phoneNumber, String verifyCode) {
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .phoneLogin(phoneNumber, verifyCode))
                .subscribeWith(new TipRequestSubscriber<Data_Token>() {
                    @Override
                    protected void onSuccess(Data_Token data_token) {
                        LoginSuccess(data_token);
                    }
                });
    }

    private void LoginSuccess(Data_Token data) {
        if (TokenUtils.handleLoginSuccess(data))  popToBack();
        else XToastUtils.error("登录失败");
    }

    private class TextChange implements TextWatcher{
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
        @Override
        public void afterTextChanged(Editable s) {
            boolean a = !StringUtils.isEmpty(etPhoneNumber.getEditValue().trim());
            boolean b =  !StringUtils.isEmpty(etVerifyCode.getEditValue().trim());
            updateConfirmBt(b && a);
            updateVerifyCodeBt(a);
        }
    }

    private void updateVerifyCodeBt(boolean a) {
        btnGetVerifyCode.setEnabled(a);
    }

    private void updateConfirmBt(boolean b) {
        btnLogin.setBackground(ResUtils.getDrawable(b?R.drawable.park_selector_bg_loginbt_normal :R.drawable.park_shape_bg_loginbt_press));
    }
}
